# -*- coding: UTF-8 -*-

import urllib2

import kivy
from ui.hat_widget import HatWidget, open_ok_popup
from model import gamestate
from model.json_loader import JsonLoader
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
import urllib2
import socket
from constants import MIN_PIN_LENGTH, MAX_PIN_LENGTH


class Join(HatWidget):
    def __init__(self, gamestate, presenter, **kwargs):
        super(Join, self).__init__(presenter, **kwargs)
        self.host = presenter.settings.game.server_name
        self.gamestate = gamestate
        self.next_button.enabled = False
        self.is_correct_id = False
        self.is_correct_pin = False
        if gamestate.remote_id is not None:
            self.game_id.text = str(gamestate.remote_id)
            self.pin_code.text = str(gamestate.pin_code)
            self.is_correct_id = True
            self.is_correct_pin = True
        self.game_id.focus = True
        if self.gamestate.current_added_player is not None:
            player_json = {
                u'name': self.gamestate.current_added_player.name,
                u'words': [],
                u'id': gamestate.remote_id,
                u'pin': gamestate.pin_code
            }
            for word in gamestate.current_added_player.words:
                player_json[u'words'].append(word.text)
            loader = JsonLoader()
            try:
                loader.dump_to_url('{}/add_player_from_json'.format(self.host),
                                   player_json)
            except urllib2.HTTPError as e:
                if e.code == 409:
                    open_ok_popup(_('User name already used'),
                                  _('Please use another name'), self)
                elif e.code == 424:
                    open_ok_popup(_('Error'),
                                  _('You cannot join this game'),
                                  self)
                else:
                    open_ok_popup(_('Error'), _('Network error'), self)
            except:
                open_ok_popup(_('Error'), _('Unknown error'), self)
            self.gamestate.current_added_player = None
        self.open_numpad = False

    def go_back(self):
        self.gamestate.clear()
        self.presenter.change_phase(gamestate.Phase.WELCOME)

    def go_next(self):
        loader = JsonLoader()
        try:
            data = loader.load_from_url(self.host +
                                        '/game_template_json?game_id=' +
                                        self.game_id.text + '&pin='
                                        + self.pin_code.text + '&join=1')
            self.gamestate.remote_id = int(self.game_id.text)
            self.gamestate.pin_code = int(self.pin_code.text)
            self.gamestate.is_joining = True
            self.gamestate.settings = gamestate.Settings()
            self.gamestate.settings.words_number =\
                data[u'settings'][u'word_count']
            self.gamestate.players = gamestate.Players([])
            self.presenter.change_phase(gamestate.Phase.ADD_PLAYER)
        except urllib2.HTTPError as msg:
            if msg.code == 404:
                error_text = _('Game not found.\nCheck your game-id')
            elif msg.code == 403:
                error_text = _('Incorrect PIN number')
            elif msg.code == 424:
                error_text = _('You cannot join this game')
            else:
                error_text = _('Network error')
            open_ok_popup(_('Error'), error_text, self)
        except urllib2.URLError:
            open_ok_popup(_('Error'), _('Network error'), self)
        except socket.timeout:
            open_ok_popup(_('Error'), _('Network error'), self)
        except:
            open_ok_popup(_('Error'), _('Unknown error'), self)

    def try_go_next(self):
        if self.next_button.enabled:
            self.go_next()

    def check_id(self):
        self.is_correct_id = self.game_id.text.isdigit()
        self.next_button.enabled = (self.is_correct_id and
                                    self.is_correct_pin)

    def check_pin(self):
        self.is_correct_pin =\
            (self.pin_code.text.isdigit() and
             len(self.pin_code.text) <= MAX_PIN_LENGTH
             and len(self.pin_code.text) >= MIN_PIN_LENGTH)
        self.next_button.enabled = (self.is_correct_id and self.is_correct_pin)
